package com.viewstreet.beanspice;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import com.viewstreet.beanspice.processor.BeanSpiceProcessor;

// TODO: Auto-generated Javadoc
/**
 * The Class BeanSpiceMojo.
 */
@Mojo(name = "compile", defaultPhase = LifecyclePhase.PROCESS_SOURCES)
public class BeanSpiceMojo extends AbstractMojo {
	/**
	 * Location of the file.
	 */
	@Parameter(defaultValue = "${project.build.directory}/generated-sources", property = "sources", required = true)
	private File srcDirectory;

	/** The spice directory. */
	@Parameter(property = "spiceSrc", required = false)
	private File spiceDirectory;

	/** The Maven Project Object. */
	@Parameter(defaultValue = "${project}", readonly = true, required = true)
	protected MavenProject project;

	/** The m_local repository. */
	@Parameter(defaultValue = "${localRepository}")
	protected ArtifactRepository m_localRepository;

	/** The local repository. */
	@Parameter(defaultValue = "${localRepository}")
	private org.apache.maven.artifact.repository.ArtifactRepository localRepository;

	/** The remote repositories. */
	@SuppressWarnings("rawtypes")
	@Parameter(defaultValue = "${project.remoteArtifactRepositories}")
	private java.util.List remoteRepositories;

	/** The artifact factory. */
	@SuppressWarnings("deprecation")
	@Component
	private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;

	/** The resolver. */
	@Component
	private org.apache.maven.artifact.resolver.ArtifactResolver resolver;

	/* (non-Javadoc)
	 * @see org.apache.maven.plugin.AbstractMojo#execute()
	 */
	public void execute() throws MojoExecutionException {

		getLog().info("Using Generated Source root of :" + srcDirectory);
		if (spiceDirectory == null) {
			spiceDirectory = new File(project.getCompileSourceRoots().get(0)
					.toString());
		}
		getLog().info("Using Spice Source root of :" + spiceDirectory);

		List<String> runClasspath = new ArrayList<String>();
		runClasspath.addAll(getDependencies());
		getLog().debug("Using Classpath of");
		for (String cpe : runClasspath) {
			getLog().debug("\t" + cpe);
		}

		if (!srcDirectory.exists()) {
			srcDirectory.mkdirs();
		}

		try {
			BeanSpiceProcessor processor = new BeanSpiceProcessor(new File []{srcDirectory},
					runClasspath);
			processor.process(spiceDirectory);
		} catch (Exception e) {
			throw new MojoExecutionException("Error processing spice files ", e);
		} finally {
		}
	}

	/**
	 * Gets the dependencies.
	 *
	 * @return the dependencies
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	private List<String> getDependencies() {
		final List<Dependency> dependencies = project.getDependencies();
		ArrayList<String> deps = new ArrayList<String>();
		for (Dependency d : dependencies) {

			final Artifact artifact = artifactFactory
					.createArtifactWithClassifier(d.getGroupId(),
							d.getArtifactId(), d.getVersion(), d.getType(),
							d.getClassifier());

			try {
				resolver.resolve(artifact, remoteRepositories, localRepository);
			} catch (Exception e) {
				getLog().error("Unable to resolve artifact",e);
			}

			File artifactFile = artifact.getFile();
			deps.add(artifactFile.getAbsolutePath());
		}
		return deps;
	}

}
